<?php
namespace Wx\Controller;
use Think\Controller;
class AuthController extends Controller {
	
	//用户授权获取code
    public function index(){
		//授权完跳转的网址
		$path = $_REQUEST['path'];
		//用户同意授权后回调的网址.必须使用url对回调网址进行编码，我们也将授权完跳转对网址,
		$redirect_uri = urlencode('http://'.$_SERVER['HTTP_HOST'].'/Wx/auth/callback/');
		header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('WX_API.appid').'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.$path.'#wechat_redirect');
	}//end fun
	
	//获取code后的回调函数
	public function callBack(){
		//dump($_REQUEST);
		//获取到的code
		$code = $_REQUEST['code'];
		//授权结束后的回调网址
		$path = $_REQUEST['state'];
		//获取access_token
		$curl = curl_init();
		curl_setopt($curl,CURLOPT_URL,'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.C('WX_API.appid').'&secret='.C('WX_API.secret').'&code='.$code.'&grant_type=authorization_code ');
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
		//获取access_token和openid,转换为数组
		$data = json_decode(curl_exec($curl),true);

		//如果获取成功，根据access_token和openid获取用户的基本信息
		if($data != null && $data['access_token']){
			session('access_token',$data['access_token']);
			//获取用户的基本信息，并将用户的唯一标识保存在session中
			curl_setopt($curl,CURLOPT_URL,'https://api.weixin.qq.com/sns/userinfo?access_token='.$data['access_token'].'&openid='.$data['openid'].'&lang=zh_CN');
			$user_data = json_decode(curl_exec($curl),true);
			//dump($user_data);
			if($user_data != null && $user_data['openid']){
				curl_close($curl);
				//将用户信息存在数据库中,同时将用户在数据库中唯一的标识保存在session中
				$array = array();
				$array['openid'] = $user_data['openid'];
				$array['nickname'] = $user_data['nickname'];
				$array['avatar'] = $user_data['headimgurl'];
				//我这里只存储了用户的openid,nickname,avatar
				$model = M('member');
				//先判断用户数据是不是已经存储了，如果存储了获取用户在数据库中的唯一标识
				$getuser = $model->where(['openid'=>$array['openid']])->find();
				if($getuser){
					//老用户
					//头像昵称实时更新
					$array['logintime'] = time();
					$model->where(['id'=>$getuser['id']])->save($array);
					
					$store = D("shop_store");
					$store_info = $store->where("status != 0 AND u_id= {$getuser['id']}")->find();
					session('s_id',$store_info['id']);  //设置session——用户店铺id
					//设置登录信息
					session('u_type',$getuser['u_type']);  //设置session——用户类型
					session('u_id',$getuser['id']);  //设置session——用户id
					session('nickname',$array['nickname']);  //设置session——用户昵称
				}else{
					//新增用户
					$array['logintime'] = time();
					$array['createtime'] = time();
					$user_id = $model->add($array);
					//设置登录信息
					session('u_id',$user_id);  //设置session——用户id
					session('s_id',null);  //设置session——用户店铺id
					session('nickname',$array['nickname']);  //设置session——用户昵称
				}
				
				session('openid',$array['openid']);  //设置session——微信openid
				
				//跳转网页
				header('Location:'.$path);
			}else{
				curl_close($curl);
				exit('获取用户信息失败！');
			}
			
		}else{
			curl_close($curl);
			exit('微信授权失败');
		}
	}//end fun
}//end class